package com.shenzhen.group.common.card.operation;

import com.shenzhen.group.common.card.Card;
import com.shenzhen.group.common.entity.CardGroupBase;
import com.shenzhen.group.common.entity.HandCardGroupBase;
import com.shenzhen.group.common.game.Position;
import com.shenzhen.group.common.player.Player;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @description: 牌组操作类
 * @author tooStronger
 * @date 2021/9/20
 */
@Slf4j
public abstract class AbstractCardOperation implements CardOperation{

    private final Integer oneSendSum;
    private final Integer cardNumSum;

    public AbstractCardOperation(Integer oneSendSum, Integer cardNumSum) {
        this.oneSendSum = oneSendSum;
        this.cardNumSum = cardNumSum;
        curCardCount.set(0);
    }

    /*** 当前发牌位置 */
    ThreadLocal<Integer> curCardCount = new ThreadLocal<>();
    /*** 随机数 */
    protected static final Random RANDOM = new Random();

    @Override
    public void dealCards(CardGroupBase cardGroup, List<Position> positions) {
        washCard(cardGroup);
        int positionCount = positions.size();
        int oneTimeSendCount = positionCount * oneSendSum;
        if (oneTimeSendCount > cardNumSum) {
            throw new RuntimeException("card not enough");
        }
        Integer curCardNumPos = curCardCount.get();
        if (curCardNumPos + oneTimeSendCount > cardNumSum) {
            washCard(cardGroup);
            curCardNumPos = 0;
            curCardCount.set(0);
        }
        // 牌组
        List<Card> cards = cardGroup.getCards();
        // 当前牌组位置
        int curPos = curCardNumPos;
        // 起始发牌位置
        int startPost = RANDOM.nextInt(positionCount);
        int nextIndex = 0;
        while (nextIndex != positionCount) {
            // 取起始发牌位子
            Position position = positions.get(startPost);
            // 生成手牌
            HandCardGroupBase handCardGroupBases = generateHandCard(curPos, cards, positionCount);
            position.setHandCardGroupBase(handCardGroupBases);
            // 位置偏移
            curPos++;
            // 下一个位置
            startPost = (startPost + 1) % positionCount;
            // 轮询
            nextIndex++;
        }
        curCardCount.set(curCardNumPos + oneTimeSendCount);
        printCardInfo(positions);
    }

    private void printCardInfo(List<Position> positions) {
        for (Position position : positions) {
            Player player = position.getPlayer();
            HandCardGroupBase handCardGroupBase = position.getHandCardGroupBase();
            log.info("玩家：{} \t的牌是 {}", player.getName(), handCardGroupBase.displayCard());
        }
    }

    protected abstract HandCardGroupBase generateHandCard(Integer curPos, List<Card> cards, int positionCount);
}
